//
//  WXWebView.m
//  TestWeb
//
//  Created by tianlong on 2018/8/4.
//  Copyright © 2018年 tianlong. All rights reserved.
//

#import "WXWebView.h"
#import "WXJSObject.h"
#import <JavaScriptCore/JavaScriptCore.h>
#import <YYWeakProxy.h>

@interface WXWebView ()<UIWebViewDelegate>
@property (nonatomic,   weak) id webViewDelegate;
@property (nonatomic, strong) NSMutableArray *objs;
@end

@implementation WXWebView

- (NSMutableArray *)objs {
    if (!_objs) {
        _objs = [NSMutableArray array];
    }
    return _objs;
}

#pragma mark - 代理方法以及代理转发
- (void)setDelegate:(id<UIWebViewDelegate>)delegate {
    if(delegate){
        [super setDelegate:self];
        self.webViewDelegate = delegate;
    }
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    if ([self.webViewDelegate respondsToSelector:@selector(webView:shouldStartLoadWithRequest:navigationType:)]) {
       return [self.webViewDelegate webView:webView shouldStartLoadWithRequest:request navigationType:navigationType];
    }
    return YES;
}

- (void)webViewDidStartLoad:(UIWebView *)webView {
    if ([self.webViewDelegate respondsToSelector:@selector(webViewDidStartLoad:)]) {
        [self.webViewDelegate webViewDidStartLoad:webView];
    }
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    if ([self.webViewDelegate respondsToSelector:@selector(webViewDidFinishLoad:)]) {
        [self.webViewDelegate webViewDidFinishLoad:webView];
    }
    
    // 主窗口注册一下
    JSContext *mainContext = [self valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    if (mainContext) {
        [self setupJSObjectWithJSContext:mainContext];
    }
    
    // 子窗口也注册一下
    NSArray *childFrames = [self valueForKeyPath:@"documentView.webView.mainFrame.childFrames"];
    if (childFrames.count > 0) {
        for (id obj in childFrames) {
            JSContext *context = [obj valueForKeyPath:@"javaScriptContext"];
            [self setupJSObjectWithJSContext:context];
        }
    }
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    if ([self.webViewDelegate respondsToSelector:@selector(webView:didFailLoadWithError:)]) {
        [self.webViewDelegate webView:webView didFailLoadWithError:error];
    }
}

#pragma mark - 注册约定的JS运行环境
- (void)registerJSRuntimeEnvironmentWithObject:(id)obj {
    if (obj) {
        [self.objs addObject:obj];
        _jsObjects = [NSArray arrayWithArray:self.objs];
    }
}

- (void)setupJSObjectWithJSContext:(JSContext *)context {
    for (id obj in self.jsObjects) {
        if ([obj isKindOfClass:[WXJSObject class]]) {
            [(WXJSObject *)obj setWebView:self];
        }
        context[NSStringFromClass([obj class])] = [YYWeakProxy proxyWithTarget:obj];
    }
}

#pragma mark - 销毁
- (void)dealloc {
    NSLog(@"%s",__FUNCTION__);
}

@end
